package com.example.tuter.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebView;

import com.example.tuter.MyApplication;
import com.example.tuter.R;
import com.example.tuter.util.Constant;
import com.example.tuter.util.CookieUtil;
import com.example.tuter.util.SPUtils;
import com.example.tuter.util.StringUtils;
import com.example.tuter.util.ToastUtil;
import com.example.tuter.util.httpUtil.HttpFunction.SSFWAPI;
import com.example.tuter.util.httpUtil.HttpFunction.UserAPI;
import com.example.tuter.util.httpUtil.RetrofitFactory;
import com.example.tuter.webview.MyWebViewClient;

import java.io.IOException;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 *
 * 在该activity中只做一个工作，就是刷新用户在信息门户的cookie
 */
public class WebViewActivity extends BaseActivity {

    private static final String server_address = "http://ehall.tjut.edu.cn/new/index.html";
    private static final String server_login_address = "http://authserver.tjut.edu.cn/authserver/login?service=http%3A%2F%2Fehall.tjut.edu.cn%2Flogin%3Fservice%3Dhttp%3A%2F%2Fehall.tjut.edu.cn%2Fnew%2Findex.html";
    private static final String ssfw_address = "http://ssfw.tjut.edu.cn/ssfw/index.do";
    private WebView webView;
    String TAG = WebViewActivity.class.getSimpleName();
    private UserAPI userAPI;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        webView.loadUrl(server_address);
        ToastUtil.showToastLong(TAG,"登录后需要再点击师生服务才可使用完整服务\n 完成后点击退出按钮");
    }


    @Override
    protected void initData() {
        userAPI = Constant.r.create(UserAPI.class);


    }

    @Override
    protected void bindEvent() {
        View exitBtn = findViewById(R.id.exit_btn);
        //点击退出按钮，保存用户相关信息
        exitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //持久化相关信息
                SPUtils.putSchoolCookie(WebViewActivity.this, SPUtils.getSchoolCookie(WebViewActivity.this));
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        initTime();
                    }
                }).start();
                finish();
            }
        });
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_web_view);


        webView = (WebView) findViewById(R.id.wbvw);
        webView.getSettings().setJavaScriptEnabled(true);//让浏览器支持javascript
        webView.setWebViewClient(new MyWebViewClient(this));


        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setDatabaseEnabled(false);
        CookieManager.getInstance().removeAllCookies(null);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_web_view;
    }



    private void initTime() {
        Retrofit r = RetrofitFactory.getSchoolInstance();
        SSFWAPI ssfwapi = r.create(SSFWAPI.class);
        Call<ResponseBody> kxjs = ssfwapi.getKxjs(SSFWAPI.KXJS, CookieUtil.getCookieFromCookieClass(Constant.schoolCookie), SSFWAPI.Referer);
        kxjs.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                ResponseBody body = response.body();
                try {
                    //获取到字符串以后把需要的学期和周数获取出来
                    //获取最后几个input,
                    String htmlString = body.string();


                    Map<String, String> map = StringUtils.getInputTagByString(htmlString);
                    if (!map.isEmpty()) {
                        //更新当前时间信息
                        //获取到当前学期字符串
                        String xnxqdm = map.get("xnxqdm");
                        SPUtils.putCurSemester(MyApplication.getContext(), xnxqdm);

                        //获取到当前周数

                        String kszc = map.get("kszc");
                        SPUtils.putCurWeek(MyApplication.getContext(), Integer.valueOf(kszc));
                        //初始化时间后再次尝试初始化课表

                    } else {
                        ToastUtil.showToastShort(TAG,"初始化时间失败");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                ToastUtil.showToastShort(TAG,"获取时间错误");
            }
        });
    }
}